package servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@WebServlet(name = "ShoppingServlet",value = "/shop")
public class ShoppingServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        //获得购买书籍的编号
        Integer bookId =Integer.parseInt(request.getParameter("bookId"));
        //获得存放购物车的session对象（从session对象中获得）
        HttpSession session = request.getSession();
        //获得购物车( 购物车实际上就是一个map  购买商品的编号为键 ，购物商品的数量为值)
        Map<Integer,Integer> shopCar= (Map<Integer, Integer>) session.getAttribute("shopCar");
        //判断是否存在购物车
          if(shopCar==null){
               shopCar = new HashMap<>();
              //把新建的购物车放入到session对象中保存
              session.setAttribute("shopCar",shopCar);
          }
          //开始购物
           if(shopCar.containsKey(bookId)){
               //买过
               shopCar.put(bookId,shopCar.get(bookId)+1);
           }else{
               //没买过
               shopCar.put(bookId,1);
           }

       // System.out.println(shopCar);

        response.sendRedirect("showResult");

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
      doPost(request,response);
    }
}
